<template>
  <div class="container">
    <!-- 标题栏 -->
    <div class="header">
      <div class="title">消息</div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchText"
        placeholder="搜索"
        shape="round"
        background="#f7f8fa"
      />
    </div>

    <!-- 联系人列表 -->
    <div class="contact-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="loadContacts"
        >
          <van-cell
            v-for="contact in filteredContacts"
            :key="contact.id"
            clickable
            @click="goliaotian(contact)"
          >
            <template #icon>
              <van-badge :content="contact.unreadCount || ''" :show-zero="false">
                <img
                  :src="contact.avatar"
                  style="width:40px;height:40px;border-radius:50%;"
                  class="contact-avatar"
                />
              </van-badge>
            </template>
            <template #title>
              <div class="contact-info">
                <div class="contact-name">{{ contact.name }}</div>
                <div class="contact-time">{{ formatTime(contact.lastActiveTime) }}</div>
              </div>
              <div class="contact-message">{{ contact.lastMessage || '暂无消息' }}</div>
            </template>
          </van-cell>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { showToast } from 'vant';
import type { ChatContact } from '../services/chatService';
import { getChatContacts } from '../services/chatService';
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const router = useRouter();
const currentUserId = ref<string | null>(store.useStore.mId || 'patient1');
const contacts = ref<ChatContact[]>([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const searchText = ref('');

const filteredContacts = computed(() => {
  if (!searchText.value) return contacts.value;
  const searchLower = searchText.value.toLowerCase();
  return contacts.value.filter(contact => 
    contact.name.toLowerCase().includes(searchLower) ||
    (contact.lastMessage && contact.lastMessage.toLowerCase().includes(searchLower))
  );
});

const loadContacts = async () => {
  if (!currentUserId.value) {
    showToast('用户未登录');
    finished.value = true;
    return;
  }
  try {
    loading.value = true;
    const res = await getChatContacts(currentUserId.value);
    console.log('接口返回数据:', res);
    contacts.value = res;
    finished.value = true;
  } catch (error) {
    console.error('加载联系人失败:', error);
    showToast('加载失败，请重试');
    finished.value = true; // 避免一直loading
  } finally {
    loading.value = false;
  }
};

const onRefresh = async () => {
  try {
    contacts.value = [];
    finished.value = false;
    await loadContacts();
  } finally {
    refreshing.value = false;
  }
};

const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 今天之内
  if (diff < 24 * 60 * 60 * 1000) {
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
  // 一周之内
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[date.getDay()];
  }
  // 更早
  return `${date.getMonth() + 1}/${date.getDate()}`;
};

const goliaotian = (contact: ChatContact) => {
  router.push({
    path: `/chat/${contact.id}`,
    query: {
      receiverName: contact.name
    }
  });
};

onMounted(() => {
  loadContacts();
});
</script>

<style scoped>
.container {
  height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.header {
  padding: 16px;
  background: white;
  text-align: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.contact-list {
  flex: 1;
  overflow-y: auto;
}

.contact-avatar {
  margin-right: 12px;
}

.contact-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.contact-name {
  font-weight: bold;
  font-size: 16px;
}

.contact-time {
  color: #999;
  font-size: 12px;
}

.contact-message {
  color: #666;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80%;
}
</style>